function deleteFormConfirm () {
	if (confirm ('Вы действительно хотите удалить выбранные сообщения?')) $('#form_delete_mail').submit ();
}

function selectAllRows(controlCheckbox) {
	$('input.delcheck').each(function() {
		if ($(controlCheckbox).attr('checked') != $(this).attr('checked')) {
			$(this).change();
		}
		$(this).attr('checked', $(controlCheckbox).attr('checked') ? 'checked' : '');
	});
}

var FriendsSelection = {
	friendsLoaded: false,
	
	// DOM
	wrapper: null,
	label: null,
	input: null,
	button: null,
	list: null,
	
	friends: [],
	
	init: function() {
		var __self = this;
		
		this.wrapper = $('<div>').addClass('friend-selection');
		
		this.label = $('<div>')
			.addClass('label')
			.text('введите логин друга')
			.click(function() { $('#friend_input').focus(); });
		
		this.input = $('<div>')
			.addClass('input')
			.append(
				$('<input>').attr({
					type: 'text',
					name: 'friend_name',
					id: 'friend_input',
					value: '',
					autocomplete: 'off'
				})
				.keyup(function(e) {
					if (e.keyCode != 38 && e.keyCode != 40) {
						__self.filter($(this).val());
					}
				})
				.focus(function() {
					__self.showFriends();
					
					__self.wrapper.addClass('focused');
					
					if ($(this).val() != '') {
						__self.filter($(this).val());
					}
					
					$(document)
						.bind('mousedown', __self.blur)
						.bind('keydown', function(e) {
							if (e.keyCode == 9) { // TAB
								FriendsSelection.forceBlur();
							}
							else if (e.keyCode == 40) { // down
								FriendsSelection.down();
							}
							else if (e.keyCode == 38) { // up
								FriendsSelection.up();
							}
						})
				})
			);
			
		this.list = $('<div>')
			.addClass('list')
			.attr('id', 'friends_list')
			.append(
				$('<ul>')
					.attr('id', 'temp_friends_list')
					.hide()
			)
			.append(
				$('<div>')
					.addClass('not-find')
					.attr('id', 'not_find_label')
					.text('пользователь не найден')
			);
		
		this.button = $('<div>')
			.addClass('button')
			.mouseover(function() { $(this).addClass('focused'); })
			.mouseout(function() { $(this).removeClass('focused'); })
			.click(function() { $('#friend_input').focus(); });
			
		this.wrapper
			.append(this.label)
			.append(this.button)
			.append(this.input)
			.append(this.list);
		
		this.setValue($('#friend_select').val());	
		
		$('#friend_select').replaceWith(this.wrapper);
		
		$('#friend_selection_wrapper').append(
			$('<input>').attr({
				type: 'hidden',
				value: '0',
				name: 'data[new][addressed_user_id]',
				id: 'addressed_user_id'
			})
		);
	},
	
	/**
	 * Move selection down
	 */
	down: function() {
		var mainList = $('#main_friends_list');
		var tempList = $('#temp_friends_list');
		
		var selected = this.getSelected();
		
		if (selected.size()) {
			var next = selected.next();
			
			if (next.size()) {
				next.addClass('selected');
				selected.removeClass('selected');
			}
		} else {
			if (mainList.css('display') == 'none') {
				tempList.children(':first').addClass('selected');
			} else {
				mainList.children(':first').addClass('selected');
			}
		}
		
		$('#friend_input').val(this.getSelected().find('a').text());
	},
	
	/**
	 * Move selection up
	 */
	up: function() {
		var mainList = $('#main_friends_list');
		var tempList = $('#temp_friends_list');
		
		var selected = this.getSelected();
		
		if (selected.size()) {
			var prev = selected.prev();
			
			if (prev.size()) {
				prev.addClass('selected');
				selected.removeClass('selected');
			}
		} else {
			if (mainList.css('display') == 'none') {
				tempList.children(':last').addClass('selected');
			} else {
				mainList.children(':last').addClass('selected');
			}
		}
		
		$('#friend_input').val(this.getSelected().find('a').text());
	},
	
	/**
	 * Filter friends list
	 */
	filter: function(chars) {
		var mainList = $('#main_friends_list');
		var tempList = $('#temp_friends_list');
		
		$('#not_find_label').hide();
		
		this.clearSelection();
		
		if (chars == '') {
			tempList.empty().hide();
			mainList.show();
			
			return;
		}
		
		mainList.hide();
		tempList.empty().show(); // clear and show temp list
		
		var regexp = new RegExp(chars, 'i');
		
		// find input text in friends
		$.each(this.friends, function(i, values) {
			var login = values[0];
			
			if (regexp.test(login)) {
				tempList.append(
					$('<li>')
						.addClass(!tempList.children().size() ? 'selected' : '') // select first element
						.append(
							$('<a>')
								.attr('href', '#')
								.html(login.replace(regexp, "<b>$&</b>"))
								.mousedown(function() {
									FriendsSelection.setFriend(login);
									return false;
								})
						)
						.mouseover(function() {
							FriendsSelection.clearSelection();
							$(this).addClass('selected');
						})
						.mouseout(function() {
							FriendsSelection.clearSelection();
							$(this).removeClass('selected');
						})
				);
			}
		});
		
		if (chars != '' && !tempList.children().size()) {
			$('#not_find_label').show();
		}
	},
	
	/**
	 * Simulate input blur by a mouse click
	 */
	blur: function(e) {
		var __self = FriendsSelection;
		
		if (!__self.wrapper.isMouseOn(e.pageX, e.pageY) || (__self.list.css('display') == 'none' &&  !__self.list.isMouseOn(e.pageX, e.pageY))) {
			__self.checkInput();
			__self.hideFriends();
			
			__self.wrapper.removeClass('focused');
			
			if($('#friend_input').val() == '') {
				__self.label.removeClass('hidden');
			} else {
				__self.label.addClass('hidden');
			}
			
			$('#friend_input').blur();
			
			$(document)
				.unbind('mousedown', __self.blur)
				.unbind('keydown');
		}
	},
	
	/**
	 * Simulate input blur by press TAB key
	 */
	forceBlur: function() {
		this.checkInput();
		this.hideFriends();
			
		this.wrapper.removeClass('focused');
		
		if($('#friend_input').val() == '') {
			this.label.removeClass('hidden');
		} else {
			this.label.addClass('hidden');
		}
		
		$('#friend_input').blur();
		
		$(document)
			.unbind('mousedown', this.blur)
			.unbind('keydown');
	},
	
	/**
	 * Check friends list and put to input selected item
	 */
	checkInput: function() {
		var input = $('#friend_input');
		var inputLogin = input.val();
		
		if (inputLogin == '') {
			return;
		}
		
		var selected = this.list.find('li.selected:first');
		
		if (selected.size()) { // Somebody selected
			var selectedLogin = selected.children('a').text();
		
			input.val(selectedLogin);
			
			// Get user id
			for(i = 0; i < this.friends.length; ++i) {
				var login = this.friends[i][0];
				var friendId = this.friends[i][1];
				
				if (login == selectedLogin) {
					$('#addressed_user_id').val(friendId);
				}
			}
		}
		else { // Nobody selected, search input text in friends
			 for(i = 0; i < this.friends.length; ++i) {
				var login = this.friends[i][0];
				var friendId = this.friends[i][1];
				
				if (login.toLowerCase() == inputLogin.toLowerCase()) {
					input.val(login);
					$('#addressed_user_id').val(friendId);
				}
			}
		}
		
		this.clearSelection();
	},
	
	/**
	 * Hide friends list
	 */
	hideFriends: function() {
		$('#temp_friends_list').empty().hide();
		$('#main_friends_list').show();
		
		this.list.hide();
	},
	
	/**
	 * Put user login to input
	 */
	setFriend: function(userLogin) {
		$('#friend_input').val(userLogin);
		
		this.forceBlur();
	},
	
	/**
	 * Put friend login to input from old select
	 */
	setValue: function(userId) {
		alert("setValue!!!");
	},
	
	/**
	 * Return selected LI element or false
	 */
	getSelected: function() {
		return this.list.find('li.selected:first');
	},
	
	/**
	 * Clear selection in friends list
	 */
	clearSelection: function() {
		this.list.find('li.selected').removeClass('selected');
	},
	
	/**
	 * Show friends list
	 */
	showFriends: function() {
		var __self = this;
		
		$('#not_find_label').hide();
		
		if (this.friendsLoaded) {
			this.list.show();
			return false;
		}
		
		$.ajax ({
			url: baseURI + '/users/ajax_xml_get_user_friends/',
			dataType: 'xml',
			type: 'get',
			error: function () {
				new Error("Ошибка при загрузке списка друзей!");
				__self.friendsLoaded = true;
			},
			beforeSend: function() {
				__self.list
					.addClass('loading')
					.show();
			},
			complete: function() {
				__self.list.removeClass('loading');
			},
			success: function (xml) {
				var ul = $('<ul>').attr('id', 'main_friends_list');
				
				$(xml).find('object').each(function() {
					var login = $(this).find('property[name=user_login] > value').text();
					
					FriendsSelection.friends.push([login, $(this).find('property[name=friend_id] > value').text()]);
					
					ul.append(
						$('<li>')
							.append(
								$('<a>')
									.attr('href', '#')
									.text(login)
									.mousedown(function() {
										FriendsSelection.setFriend(login);
										return false;
									})
							)
							.mouseover(function() {
								FriendsSelection.clearSelection();
								$(this).addClass('selected');
							})
							.mouseout(function() {
								FriendsSelection.clearSelection();
								$(this).removeClass('selected');
							})
					);
				});
				
				__self.list.append(ul);
				
				__self.friendsLoaded = true;
			}
		});
	}
};